<script>
// @ts-nocheck

  import { writable } from 'svelte/store';
  import { goto } from '$app/navigation';
  let topics = writable([]);

  let newTopic = {
    title: '',
    description: ''
  };

  let newComment = {
    name: '',
    text: '',
    topicId: null
  };

  const addTopic = () => {
    if (newTopic.title && newTopic.description) {
      topics.update(currentTopics => [
        ...currentTopics,
        {
          ...newTopic,
          id: Date.now(),
          comments: []
        }
      ]);
      newTopic.title = '';
      newTopic.description = '';
    }
  };

  const addComment = () => {
    if (newComment.name && newComment.text && newComment.topicId !== null) {
      topics.update(currentTopics =>
        currentTopics.map(topic =>
          topic.id === newComment.topicId
            ? {
                ...topic,
                comments: [
                  ...topic.comments,
                  {
                    ...newComment,
                    id: Date.now(),
                    timestamp: new Date().toLocaleString(),
                    likes: 0,
                    dislikes: 0,
                    userReaction: null,
                    replies: []
                  }
                ]
              }
            : topic
        )
      );
      newComment.name = '';
      newComment.text = '';
    }
  };

  const addReply = (topicId, commentId, replyText) => {
    if (replyText) {
      topics.update(currentTopics =>
        currentTopics.map(topic =>
          topic.id === topicId
            ? {
                ...topic,
                comments: topic.comments.map(comment =>
                  comment.id === commentId
                    ? {
                        ...comment,
                        replies: [
                          ...comment.replies,
                          {
                            id: Date.now(),
                            text: replyText,
                            timestamp: new Date().toLocaleString(),
                            likes: 0,
                            dislikes: 0,
                            userReaction: null
                          }
                        ]
                      }
                    : comment
                )
              }
            : topic
        )
      );
    }
  };

  const toggleLike = (topicId, commentId, replyId = null) => {
    topics.update(currentTopics =>
      currentTopics.map(topic => {
        if (topic.id === topicId) {
          return {
            ...topic,
            comments: topic.comments.map(comment => {
              if (comment.id === commentId) {
                if (replyId === null) {
                  if (comment.userReaction === 'like') {
                    return { ...comment, likes: comment.likes - 1, userReaction: null };
                  } else if (comment.userReaction === 'dislike') {
                    return {
                      ...comment,
                      likes: comment.likes + 1,
                      dislikes: comment.dislikes - 1,
                      userReaction: 'like'
                    };
                  } else {
                    return { ...comment, likes: comment.likes + 1, userReaction: 'like' };
                  }
                } else {
                  return {
                    ...comment,
                    replies: comment.replies.map(reply =>
                      reply.id === replyId
                        ? reply.userReaction === 'like'
                          ? { ...reply, likes: reply.likes - 1, userReaction: null }
                          : reply.userReaction === 'dislike'
                          ? {
                              ...reply,
                              likes: reply.likes + 1,
                              dislikes: reply.dislikes - 1,
                              userReaction: 'like'
                            }
                          : { ...reply, likes: reply.likes + 1, userReaction: 'like' }
                        : reply
                    )
                  };
                }
              }
              return comment;
            })
          };
        }
        return topic;
      })
    );
  };

  const toggleDislike = (topicId, commentId, replyId = null) => {
    topics.update(currentTopics =>
      currentTopics.map(topic => {
        if (topic.id === topicId) {
          return {
            ...topic,
            comments: topic.comments.map(comment => {
              if (comment.id === commentId) {
                if (replyId === null) {
                  if (comment.userReaction === 'dislike') {
                    return { ...comment, dislikes: comment.dislikes - 1, userReaction: null };
                  } else if (comment.userReaction === 'like') {
                    return {
                      ...comment,
                      dislikes: comment.dislikes + 1,
                      likes: comment.likes - 1,
                      userReaction: 'dislike'
                    };
                  } else {
                    return { ...comment, dislikes: comment.dislikes + 1, userReaction: 'dislike' };
                  }
                } else {
                  return {
                    ...comment,
                    replies: comment.replies.map(reply =>
                      reply.id === replyId
                        ? reply.userReaction === 'dislike'
                          ? { ...reply, dislikes: reply.dislikes - 1, userReaction: null }
                          : reply.userReaction === 'like'
                          ? {
                              ...reply,
                              dislikes: reply.dislikes + 1,
                              likes: reply.likes - 1,
                              userReaction: 'dislike'
                            }
                          : { ...reply, dislikes: reply.dislikes + 1, userReaction: 'dislike' }
                        : reply
                    )
                  };
                }
              }
              return comment;
            })
          };
        }
        return topic;
      })
    );
  };

  let replyTexts = writable({});

  function setReplyText(commentId, text) {
    replyTexts.update(texts => ({ ...texts, [commentId]: text }));
  }
</script>

<style>
  .topic-section {
    max-width: 600px;
    margin: 0 auto;
  }
  .topic-form,
  .comment-form {
    display: flex;
    flex-direction: column;
    gap: 1rem;
    margin-bottom: 2rem;
  }
  .topic-form input,
  .topic-form textarea,
  .comment-form input,
  .comment-form textarea {
    padding: 0.5rem;
    font-size: 1rem;
  }
  .topic-list,
  .comment-list {
    list-style: none;
    padding: 0;
  }
  .topic,
  .comment,
  .reply {
    padding: 1rem;
    border-bottom: 1px solid #ccc;
  }
  .timestamp {
    color: gray;
    font-size: 0.8rem;
  }
  .like-dislike {
    display: flex;
    gap: 0.5rem;
    margin-bottom: 0.5rem;
  }
  .like-dislike button {
    background: none;
    border: none;
    cursor: pointer;
  }
  .reply-form {
    margin-top: 1rem;
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
  }
  .replies {
    margin-left: 2rem;
  }
</style>

<div class="topic-section">
  <div class="topic-form">
    <input
      type="text"
      placeholder="Topic title"
      bind:value={newTopic.title}
    />
    <textarea
      placeholder="Topic description"
      bind:value={newTopic.description}
    ></textarea>
    <button on:click={addTopic}>Create Topic</button>
  </div>

  <ul class="topic-list">
    {#each $topics as topic (topic.id)}
      <li class="topic">
        <h3>{topic.title}</h3>
        <p>{topic.description}</p>
        <div class="comment-section">
          <div class="comment-form">
            <input
              type="text"
              placeholder="Your name"
              bind:value={newComment.name}
            />
            <textarea
              placeholder="Your comment"
              bind:value={newComment.text}
            ></textarea>
            <button on:click={() => { newComment.topicId = topic.id; addComment(); }}>Add Comment</button>
          </div>

          <ul class="comment-list">
            {#each topic.comments as comment (comment.id)}
              <li class="comment">
                <strong>{comment.name}</strong>
                <p>{comment.text}</p>
                <div class="like-dislike">
                  <button on:click={() => toggleLike(topic.id, comment.id)}>
                    👍 {comment.likes}
                  </button>
                  <button on:click={() => toggleDislike(topic.id, comment.id)}>
                    👎 {comment.dislikes}
                  </button>
                </div>
                <div class="timestamp">{comment.timestamp}</div>
                <div class="reply-form">
                  <input
                    type="text"
                    placeholder="Reply to this comment"
                    value={$replyTexts[comment.id] || ''}
                    on:input={(e) => setReplyText(comment.id, e.target.value)}
                  />
                  <button
                    on:click={() => {
                      addReply(topic.id, comment.id, $replyTexts[comment.id]);
                      setReplyText(comment.id, '');
                    }}
                  >
                    Reply
                  </button>
                </div>
                <ul class="replies">
                  {#each comment.replies as reply (reply.id)}
                    <li class="reply">
                      <p>{reply.text}</p>
                      <div class="like-dislike">
                        <button on:click={() => toggleLike(topic.id, comment.id, reply.id)}>
                          👍 {reply.likes}
                        </button>
                        <button on:click={() => toggleDislike(topic.id, comment.id, reply.id)}>
                          👎 {reply.dislikes}
                        </button>
                      </div>
                      <div class="timestamp">{reply.timestamp}</div>
                    </li>
                  {/each}
                </ul>
              </li>
            {/each}
          </ul>
        </div>
      </li>
    {/each}
  </ul>
</div>
